package com.example.ymm.util;


import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Component
@Slf4j
public class CosUtil {

    @Value("${qcloud.secretId}")
    String secretId;

    @Value("${qcloud.secretKey}")
    String secretKey;

    @Value("${qcloud.bucketName}")
    String bucketName;

    @Value("${qcloud.domain}")
    String domain;

    // 从输入流进行读取并上传到COS
    public String uploadImgFromStream(InputStream input,String fileName,int contentLength) {
        String url = null;
        try {

            // 1 初始化用户身份信息(secretId, secretKey)
            COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
            // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
            ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
            // 3 生成cos客户端
            COSClient cosclient = new COSClient(cred, clientConfig);
            // bucket名需包含appid

//            File localFile = new File("C:\\Users\\Administrator\\Desktop\\22.jpg");
            String key = createImgUrl(fileName);
            url = domain + key;
//           InputStream input = new ByteArrayInputStream(new byte[10]);
//            FileInputStream input = new FileInputStream(localFile);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据，存在内存OOM的情况
          //  objectMetadata.setContentLength(10);
            objectMetadata.setContentLength(contentLength);
            // 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
            objectMetadata.setContentType("image/jpeg");

            PutObjectRequest putObjectRequest =new PutObjectRequest(bucketName, key, input, objectMetadata);
            //    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);

            // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
            putObjectRequest.setStorageClass(StorageClass.Standard_IA);
            try {
                PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
                // putobjectResult会返回文件的etag
                String etag = putObjectResult.getETag();
            } catch (CosServiceException e) {
                e.printStackTrace();
            } catch (CosClientException e) {
                e.printStackTrace();
            }

            // 关闭客户端
            cosclient.shutdown();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return url;
    }

    public String createImgUrl(String fileName) {
        String url = "", prefix = "/attach";
        String fileSuffix = "";//文件后缀 .png
        String[] splitSuffix = fileName.split("\\.");
        fileSuffix = splitSuffix[1];

        String date_str = DateKit.dateFormat(new Date(), "yyyy-MM-dd");
        String[] split = date_str.split("-");
        String year = split[0];
        String month = split[1];
        String uuid = UuidUtils.getUUID();
        url = prefix + "/" + year + "/" + month + "/" + uuid + "." + fileSuffix;
        return url;
    }

    /**
     * 获取字符串md5哈希
     *
     * @param inputStr
     * @return
     */
    public static String getMd5ToString(String inputStr) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashByte = md.digest(inputStr.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte item : hashByte) {
                sb.append(String.format("%02x", item));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String md5ToString = UuidUtils.getUUID();
        System.out.println(md5ToString);
    }

}
